package com.catfairy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.catfairy.blog.api.BlogServiceApi;
import com.catfairy.blog.api.pojo.BlogInfoResponse;
import com.catfairy.common.exception.BlogException;
import com.catfairy.common.pojo.Result;
import com.catfairy.common.utils.*;
import com.catfairy.user.api.pojo.UserInfoRegisterRequest;
import com.catfairy.user.api.pojo.UserInfoRequest;
import com.catfairy.user.api.pojo.UserInfoResponse;
import com.catfairy.user.api.pojo.UserLoginResponse;
import com.catfairy.user.common.dataobject.UserInfo;
import com.catfairy.user.constant.Constants;
import com.catfairy.user.mapper.UserInfoMapper;
import com.catfairy.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.catfairy.user.convert.BeanConvert.convertUserInfoByEncrypt;
@Slf4j
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private BlogServiceApi blogServiceApi;
    @Autowired
    private Redis redis;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private static final long EXPIRE_TIME = 14*24*60*60;
    private static final String USER_PREFIX = "user";
    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
        UserInfo userInfo = queryUserInfo(user.getUserName());
        if (userInfo==null || userInfo.getId()==null){
            throw new BlogException("用户不存在");
        }
//        if (!user.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("用户密码不正确");
//        }
        if (!SecurityUtil.verify(user.getPassword(),userInfo.getPassword())){
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //远程调用blogApi
        //1. 根据博客ID, 获取作者ID
        Result<BlogInfoResponse> blogDeatail = blogServiceApi.getBlogDeatail(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogDeatail == null || blogDeatail.getData()==null){
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogDeatail.getData().getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public Integer register(UserInfoRegisterRequest registerRequest) {
        //校验参数: 用户名不能重复,密码,邮箱,URL格式
        checkUserInfo(registerRequest);
        //插入数据库
        UserInfo userInfo = convertUserInfoByEncrypt(registerRequest);
        try{
            int insert = userInfoMapper.insert(userInfo);
            if(insert==1){
                //存储数据到redis中
                redis.set(buildKey(userInfo.getUserName()), JSONUtil.toJSONString(userInfo),EXPIRE_TIME);
                //发送消息
                userInfo.setPassword("");
                rabbitTemplate.convertAndSend(Constants.USER_EXCHANGE_NAME,"",JSONUtil.toJSONString(userInfo));
                return userInfo.getId();
            }else {
                throw new BlogException("注册失败");
            }
        }catch (Exception e){
            log.error("注册失败, e:", e);
            throw new BlogException("注册失败");
        }
    }

    private String buildKey(String userName) {
        return redis.buildKey(USER_PREFIX,userName);
    }

    private void checkUserInfo(UserInfoRegisterRequest registerRequest) {
        UserInfo userInfo = selectUserInfoByName(registerRequest.getUserName());
        if (userInfo!=null){
            throw new BlogException("用户名已存在");
        }
        if(!RegexUtil.checkMail(registerRequest.getEmail())){
            throw new BlogException("邮箱格式不正确");
        }
        if(!RegexUtil.checkURL(registerRequest.getGithubUrl())){
            throw new BlogException("githubUrl格式不正确");
        }
    }

    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }

    private UserInfo queryUserInfo(String userName){
        //先从redis读取数据
        String key = buildKey(userName);
        boolean exists = redis.hasKey(key);
        if(exists){
            String userJson = redis.get(key);
            UserInfo userInfo = JSONUtil.parseJson(userJson, UserInfo.class);
            return userInfo == null?selectUserInfoByName(userName):userInfo;
        }else {
            UserInfo userInfo = selectUserInfoByName(userName);
            redis.set(key, JSONUtil.toJSONString(userInfo), EXPIRE_TIME);
            return userInfo;
        }
    }

    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }


}
